﻿using System.Web.UI;
using System.Web.UI.WebControls;
using ReadyApps.Common;
using ReadyApps.Common.Exceptions;

namespace ReadyApps.Wiki.Templates
{
    /// <summary>
    /// Represents the set of controls created by instantiating a template for the wiki
    /// buttons.
    /// </summary>
    class WikiControlButton
    {
        #region Properties

        /// <summary>
        /// Gets the base control of the control hierarchy of the instantiated template.
        /// </summary>
        public Control RootControl { get; private set; }

        /// <summary>
        /// Gets the control that represents the clickable <see cref="IButtonControl"/>
        /// control.
        /// </summary>
        public IButtonControl ButtonControl { get; private set; }

        #endregion

        #region Constructor

        /// <summary>
        /// Creates a new instance of a <see cref="WikiControlButton"/> with the given
        /// base control and a reference to the control implementing the
        /// <see cref="IButtonControl"/> interface.
        /// </summary>
        /// <param name="rootControl">The base control of the control hierarchy of the
        /// instantiated template.</param>
        /// <param name="buttonControl">An <see cref="IButtonControl"/> control that
        /// is the active part of the instantiated template.</param>
        public WikiControlButton(Control rootControl, IButtonControl buttonControl)
        {
            RootControl = rootControl;
            ButtonControl = buttonControl;
        }

        #endregion

        #region Static Methods

        /// <summary>
        /// Creates the control from the provided template or the default template if a custom
        /// template is not supplied.
        /// </summary>
        /// <param name="suppliedButtonTemplate">An optional parameter that can be a non-default button
        /// template</param>
        /// <returns>A <see cref="WikiControlButton"/> based on the supplied or default
        /// template.</returns>
        public static WikiControlButton GetFromTemplate(ITemplate suppliedButtonTemplate = null)
        {
            Control container = new Control();

            ITemplate buttonTemplate = suppliedButtonTemplate ?? new WikiDefaultButtonTemplate();
            buttonTemplate.InstantiateIn(container);

            Control button = WebUtilities.FindControlRecursive(container, WikiController.BUTTON_CONTROL_ID);
            if (button == null || !(button is IButtonControl))
            {
                throw new MissingControlException(WikiController.BUTTON_CONTROL_ID, typeof(IButtonControl), "button template");
            }
            button.ID = string.Empty;

            return new WikiControlButton(container, (IButtonControl)button);
        }

        #endregion
    }
}
